package io.gitee.zhangbinhub.acp.cloud.oauth.controller;

import io.gitee.zhangbinhub.acp.boot.exceptions.WebException;
import io.gitee.zhangbinhub.acp.core.common.CommonTools;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@RestController
@RequestMapping
public class TokenController {

    private final RestTemplate restTemplate;

    public TokenController(@Qualifier("acpSpringCloudResourceServerRestTemplate")
                           RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping(value = "/oauth/token", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> token(@RequestParam MultiValueMap<String, Object> paramMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Content-type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headers.add("Authorization", "Basic " + Base64.toBase64String((paramMap.getFirst("client_id") + ":" + paramMap.getFirst("client_secret")).getBytes(Charset.forName(CommonTools.getDefaultCharset()))));
        try {
            return restTemplate.exchange("http://server-oauth2/inner/oauth/token",
                    HttpMethod.POST, new HttpEntity<>(paramMap, headers), String.class);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        } catch (Exception e) {
            throw new WebException(HttpStatus.UNAUTHORIZED, e.getMessage());
        }
    }

}
